import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../data/models/download_record.dart';
import '../../../data/services/download_database_service.dart';
import '../../../data/services/mp4_download_service.dart';
import '../../../data/services/flv_download_service.dart';
import '../../../data/services/user_service.dart';
import '../views/video_player_dialog.dart';
import '../views/video_player_dialog_android.dart';
import 'dart:io'; // Added for File
import 'package:flutter/services.dart'; // Added for SystemChrome
import 'package:path_provider/path_provider.dart'; // Added for getTemporaryDirectory

class DownloadController extends GetxController {
  // 服务实例
  final DownloadDatabaseService _databaseService = DownloadDatabaseService();
  final Mp4DownloadService _mp4DownloadService = Mp4DownloadService();
  final FlvDownloadService _flvDownloadService = FlvDownloadService();

  // 当前选择的筛选索引 0:全部 1:进行中 2:已完成
  final selectedFilterIndex = 0.obs;

  // 下载记录列表
  final downloadRecords = <DownloadRecord>[].obs;

  // 是否全部暂停
  final isAllPaused = false.obs;

  // 防抖机制：记录上次更新的时间
  final Map<String, DateTime> _lastUpdateTime = {};

  @override
  void onInit() {
    super.onInit();
    _loadDownloadRecords();
    // 清理重复的等待中记录
    Future.delayed(const Duration(seconds: 1), () {
      cleanDuplicateWaitingRecords();
    });
    // 🚫 移除自动恢复中断下载任务的机制，避免删除后自动恢复
    // 改为重置异常状态，防止界面显示不一致
    Future.delayed(const Duration(seconds: 2), () {
      _resetAbnormalDownloadStatus();
    });
    // 定期清理临时文件
    Future.delayed(const Duration(seconds: 5), () {
      _cleanupTempFiles();
    });
  }

  @override
  void onClose() {
    _mp4DownloadService.dispose();
    _flvDownloadService.dispose();
    // 清理临时文件
    _cleanupTempFiles();
    super.onClose();
  }

  /// 清理临时文件
  Future<void> _cleanupTempFiles() async {
    try {
      print('🧹 开始清理临时文件...');

      // 清理HLS临时目录
      final tempDir = await getTemporaryDirectory();
      final hlsTempDir = Directory('${tempDir.path}/hls_temp');

      if (await hlsTempDir.exists()) {
        final files = await hlsTempDir.list().toList();
        int deletedCount = 0;

        for (final file in files) {
          try {
            if (file is File) {
              await file.delete();
              deletedCount++;
            } else if (file is Directory) {
              await file.delete(recursive: true);
              deletedCount++;
            }
          } catch (e) {
            print('⚠️ 删除临时文件失败: $e');
          }
        }

        print('🧹 清理完成，删除了 $deletedCount 个临时文件');
      }
    } catch (e) {
      print('❌ 清理临时文件失败: $e');
    }
  }

  /// 检查并请求存储权限
  Future<bool> _checkAndRequestStoragePermission() async {
    try {
      // 检查Android版本
      if (Platform.isAndroid) {
        var status = await Permission.manageExternalStorage.request();
        if (status.isGranted) {
          return true;
        } else if (status.isPermanentlyDenied) {
          openAppSettings();
          return true;
        }
      }

      return true;
    } catch (e) {
      print('❌ 权限检查失败: $e');
      return false;
    }
  }

  /// 加载下载记录
  Future<void> _loadDownloadRecords() async {
    try {
      final records = await _databaseService.getAllDownloadRecords();
      downloadRecords.value = records;
    } catch (e) {
      print('❌ 加载下载记录失败: $e');
      BotToast.showText(text: '加载下载记录失败');
    }
  }

  /// 开始下载视频（支持 FLV 流和 MP4 直接下载）
  Future<void> startDownload({
    required String hlsUrl,
    required String deviceName,
    required String deviceId,
    required String channelId,
    required String channelName,
    required String startTime,
    required String endTime,
    required String duration,
    required String picUrl,
  }) async {
    try {
      print('🚀 开始下载: $deviceName');
      print('📡 视频URL: $hlsUrl');

      // 判断是否为 FLV 流媒体
      final isFlvStream = _isFlvStream(hlsUrl);
      print('📊 视频类型: ${isFlvStream ? "FLV流媒体" : "MP4直接下载"}');

      // 首先检查权限
      final hasPermission = await _checkAndRequestStoragePermission();
      if (!hasPermission) {
        BotToast.showText(text: '网络环境不佳，请稍后尝试');
        return;
      }

      // 检查是否已存在相同的下载（基于URL和时间）
      final existingRecords =
          downloadRecords
              .where(
                (r) =>
                    r.videoUrl == hlsUrl &&
                    r.startTime == startTime &&
                    r.endTime == endTime,
              )
              .toList();

      if (existingRecords.isNotEmpty) {
        final existingRecord = existingRecords.first;
        if (existingRecord.status == DownloadStatus.waiting ||
            existingRecord.status == DownloadStatus.downloading) {
          BotToast.showText(text: '该视频正在下载中，请稍候');
          return;
        } else if (existingRecord.status == DownloadStatus.completed) {
          BotToast.showText(text: '下载完成，请前往我的下载进行查看');
          return;
        } else if (existingRecord.status == DownloadStatus.failed ||
            existingRecord.status == DownloadStatus.paused) {
          // 如果是失败或暂停状态，重新开始下载
          print('🔄 重新开始失败的下载: ${existingRecord.deviceName}');

          // 显示相应的提示信息
          if (existingRecord.status == DownloadStatus.failed) {
            BotToast.showText(text: '检测到失败的下载，正在重新开始...');
          } else {
            BotToast.showText(text: '检测到暂停的下载，正在重新开始...');
          }

          // 更新记录状态为等待中
          final updatedRecord = existingRecord.copyWith(
            status: DownloadStatus.waiting,
            progress: 0.0,
            speed: '0B/s',
          );

          // 更新数据库和本地列表
          await _databaseService.updateDownloadRecord(updatedRecord);
          final index = downloadRecords.indexWhere(
            (r) => r.id == existingRecord.id,
          );
          if (index >= 0) {
            downloadRecords[index] = updatedRecord;
          }

          // 根据类型选择下载服务
          if (isFlvStream) {
            await _startFlvStreamDownload(
              record: updatedRecord,
              streamUrl: hlsUrl,
              deviceName: deviceName,
              startTime: startTime,
              endTime: endTime,
              duration: duration,
            );
          } else {
            await _startMp4Download(
              record: updatedRecord,
              downloadUrl: hlsUrl,
              deviceName: deviceName,
              startTime: startTime,
              endTime: endTime,
              duration: duration,
              deviceId: deviceId,
              channelId: channelId,
              channelName: channelName,
              picUrl: picUrl,
            );
          }
          return;
        }
      }

      // 获取当前用户ID
      final userId = await _getCurrentUserId();

      // 创建下载记录
      final record = DownloadRecord(
        userId: userId,
        deviceId: deviceId,
        deviceName: deviceName,
        channelId: channelId,
        channelName: channelName,
        videoUrl: hlsUrl,
        localPath: '',
        fileName: '',
        startTime: startTime,
        endTime: endTime,
        duration: duration,
        fileSize: '0B',
        downloadedSize: '0B',
        progress: 0.0,
        speed: '0B/s',
        status: DownloadStatus.waiting,
        createdAt: DateTime.now(),
        picUrl: picUrl,
      );

      // 保存到数据库
      final id = await _databaseService.insertDownloadRecord(record);
      final savedRecord = record.copyWith(id: id);

      // 添加到列表
      downloadRecords.insert(0, savedRecord);

      print('📝 创建下载记录: ${savedRecord.deviceName} - ${savedRecord.status}');

      // 强制更新UI
      update();

      // 根据类型选择下载服务
      if (isFlvStream) {
        print('🎬 使用 FLV 流下载服务');
        await _startFlvStreamDownload(
          record: savedRecord,
          streamUrl: hlsUrl,
          deviceName: deviceName,
          startTime: startTime,
          endTime: endTime,
          duration: duration,
        );
      } else {
        print('🎬 使用 MP4 直接下载服务');
        await _startMp4Download(
          record: savedRecord,
          downloadUrl: hlsUrl,
          deviceName: deviceName,
          startTime: startTime,
          endTime: endTime,
          duration: duration,
          deviceId: deviceId,
          channelId: channelId,
          channelName: channelName,
          picUrl: picUrl,
        );
      }
    } catch (e) {
      print('❌ 开始下载失败: $e');
      BotToast.showText(text: '开始下载失败: $e');
    }
  }

  /// 判断是否为 FLV 流媒体
  bool _isFlvStream(String url) {
    // FLV 流通常包含 .flv 或特定的流媒体特征
    return url.contains('.flv') ||
        url.contains('/live/') ||
        url.contains('rtmp://') ||
        url.startsWith('rtmp://');
  }

  /// 启动 FLV 流下载
  Future<void> _startFlvStreamDownload({
    required DownloadRecord record,
    required String streamUrl,
    required String deviceName,
    required String startTime,
    required String endTime,
    required String duration,
  }) async {
    try {
      print('🎬 开始 FLV 流下载');

      // 更新状态为下载中
      final downloadingRecord = record.copyWith(
        status: DownloadStatus.downloading,
      );
      await _updateDownloadRecord(downloadingRecord);

      await _flvDownloadService.downloadStream(
        streamUrl: streamUrl,
        deviceName: deviceName,
        startTime: startTime,
        endTime: endTime,
        duration: duration,
        onProgress: (progress, speed, downloadedSize, totalSize) async {
          // 更新下载记录
          final progressRecord = record.copyWith(
            progress: progress,
            speed: speed,
            downloadedSize: downloadedSize,
            fileSize: totalSize,
            status: DownloadStatus.downloading,
          );
          await _updateDownloadRecord(progressRecord);
        },
        onComplete: (filePath, fileName) async {
          // 下载完成
          final completedRecord = record.copyWith(
            status: DownloadStatus.completed,
            progress: 1.0,
            localPath: filePath,
            fileName: fileName,
            updatedAt: DateTime.now(),
          );
          await _updateDownloadRecord(completedRecord);
          BotToast.showText(text: '下载完成，请前往我的下载进行查看');
        },
        onError: (error) async {
          // 下载失败
          final errorRecord = record.copyWith(
            status: DownloadStatus.failed,
            errorMessage: error,
            updatedAt: DateTime.now(),
          );
          await _updateDownloadRecord(errorRecord);
          BotToast.showText(text: '网络环境不佳，请稍后尝试');
        },
      );
    } catch (e) {
      print('❌ FLV 流下载失败: $e');
      final errorRecord = record.copyWith(
        status: DownloadStatus.failed,
        errorMessage: e.toString(),
      );
      await _updateDownloadRecord(errorRecord);
    }
  }

  /// 启动 MP4 直接下载
  Future<void> _startMp4Download({
    required DownloadRecord record,
    required String downloadUrl,
    required String deviceName,
    required String startTime,
    required String endTime,
    required String duration,
    required String deviceId,
    required String channelId,
    required String channelName,
    required String picUrl,
  }) async {
    await _mp4DownloadService.downloadMp4(
      downloadUrl: downloadUrl,
      deviceName: deviceName,
      startTime: startTime,
      endTime: endTime,
      duration: duration,
      recordId: record.id!,
      userId: record.userId,
      deviceId: deviceId,
      channelId: channelId,
      channelName: channelName,
      picUrl: picUrl,
      onProgress: (progressRecord) async {
        await _updateDownloadRecord(progressRecord);
      },
      onComplete: (completedRecord) async {
        await _updateDownloadRecord(completedRecord);
        BotToast.showText(text: '下载完成，请前往我的下载进行查看');
      },
      onError: (errorRecord, errorMessage) async {
        print('❌ 下载失败: ${errorRecord.deviceName} - $errorMessage');
        await _updateDownloadRecord(errorRecord);
        BotToast.showText(text: '网络环境不佳，请稍后尝试');
      },
    );
  }

  /// 使用现有记录ID开始下载MP4视频
  Future<void> startMp4DownloadWithRecordId({
    required int recordId,
    required String downloadUrl,
  }) async {
    try {
      // 查找记录
      final record = downloadRecords.firstWhere(
        (r) => r.id == recordId,
        orElse: () => throw Exception('记录不存在'),
      );

      print('🚀 使用现有记录开始MP4下载: ${record.deviceName} (ID: $recordId)');

      // 首先检查权限
      final hasPermission = await _checkAndRequestStoragePermission();
      if (!hasPermission) {
        BotToast.showText(text: '网络环境不佳，请稍后尝试');
        return;
      }

      // 更新记录状态为等待中
      final updatedRecord = record.copyWith(
        videoUrl: downloadUrl,
        status: DownloadStatus.waiting,
        downloadedSize: '0B',
        progress: 0.0,
        speed: '0B/s',
      );

      // 更新数据库和本地列表
      await _updateDownloadRecord(updatedRecord);

      // 开始下载
      await _mp4DownloadService.downloadMp4(
        downloadUrl: downloadUrl,
        deviceName: record.deviceName,
        startTime: record.startTime,
        endTime: record.endTime,
        duration: record.duration,
        recordId: recordId,
        userId: record.userId,
        deviceId: record.deviceId,
        channelId: record.channelId,
        channelName: record.channelName,
        picUrl: record.picUrl,
        onProgress: (progressRecord) async {
          await _updateDownloadRecord(progressRecord);
        },
        onComplete: (completedRecord) async {
          await _updateDownloadRecord(completedRecord);
          BotToast.showText(text: '下载完成，请前往我的下载进行查看');
        },
        onError: (errorRecord, errorMessage) async {
          print('❌ 下载失败: ${errorRecord.deviceName} - $errorMessage');
          await _updateDownloadRecord(errorRecord);
          BotToast.showText(text: '网络环境不佳，请稍后尝试');
        },
      );
    } catch (e) {
      print('❌ 使用现有记录开始下载失败: $e');
      BotToast.showText(text: '下载启动失败: $e');
    }
  }

  /// 开始下载MP4视频（直接下载）
  Future<void> startMp4Download({
    required String downloadUrl,
    required String deviceName,
    required String deviceId,
    required String channelId,
    required String channelName,
    required String startTime,
    required String endTime,
    required String duration,
    required String picUrl,
  }) async {
    try {
      print('🚀 开始MP4直接下载: $deviceName');

      // 首先检查权限
      final hasPermission = await _checkAndRequestStoragePermission();
      if (!hasPermission) {
        BotToast.showText(text: '网络环境不佳，请稍后尝试');
        return;
      }

      // 检查是否已存在相同的下载（基于URL和时间）
      final existingRecords =
          downloadRecords
              .where(
                (r) =>
                    r.videoUrl == downloadUrl &&
                    r.startTime == startTime &&
                    r.endTime == endTime,
              )
              .toList();

      if (existingRecords.isNotEmpty) {
        final existingRecord = existingRecords.first;
        if (existingRecord.status == DownloadStatus.waiting ||
            existingRecord.status == DownloadStatus.downloading) {
          BotToast.showText(text: '该视频正在下载中，请稍候');
          return;
        } else if (existingRecord.status == DownloadStatus.completed) {
          BotToast.showText(text: '下载完成，请前往我的下载进行查看');
          return;
        }
      }

      // 获取当前用户ID
      final userId = await _getCurrentUserId();

      // 创建下载记录
      final record = DownloadRecord(
        userId: userId,
        deviceId: deviceId,
        deviceName: deviceName,
        channelId: channelId,
        channelName: channelName,
        videoUrl: downloadUrl,
        localPath: '',
        fileName: '',
        startTime: startTime,
        endTime: endTime,
        duration: duration,
        fileSize: '0B',
        downloadedSize: '0B',
        progress: 0.0,
        speed: '0B/s',
        status: DownloadStatus.waiting,
        createdAt: DateTime.now(),
        picUrl: picUrl,
      );

      // 保存到数据库
      final id = await _databaseService.insertDownloadRecord(record);
      final savedRecord = record.copyWith(id: id);

      // 添加到列表
      downloadRecords.insert(0, savedRecord);

      print('📝 创建MP4下载记录: ${savedRecord.deviceName} - ${savedRecord.status}');

      // 强制更新UI
      update();

      // 开始MP4下载
      await _mp4DownloadService.downloadMp4(
        downloadUrl: downloadUrl,
        deviceName: deviceName,
        startTime: startTime,
        endTime: endTime,
        duration: duration,
        recordId: id,
        userId: userId, // 传递用户ID
        deviceId: deviceId,
        channelId: channelId,
        channelName: channelName,
        picUrl: picUrl,
        onProgress: (progressRecord) async {
          // 检查记录是否还存在（可能已被删除）
          final existingRecord = downloadRecords.firstWhere(
            (r) => r.id == progressRecord.id,
            orElse:
                () => DownloadRecord(
                  id: -1, // 不存在的记录
                  userId: 0,
                  deviceId: '',
                  deviceName: '',
                  channelId: '',
                  channelName: '',
                  videoUrl: '',
                  localPath: '',
                  fileName: '',
                  startTime: '',
                  endTime: '',
                  duration: '',
                  fileSize: '',
                  downloadedSize: '',
                  progress: 0.0,
                  speed: '',
                  status: DownloadStatus.failed,
                  createdAt: DateTime.now(),
                  picUrl: '',
                ),
          );

          // 如果记录不存在或已被删除，停止进度更新
          if (existingRecord.id == -1) {
            print('🗑️ 下载记录已被删除，停止进度更新: ${progressRecord.deviceName}');
            return;
          }

          // 检查记录状态，如果已暂停或删除，停止更新
          if (existingRecord.status == DownloadStatus.paused ||
              existingRecord.status == DownloadStatus.failed) {
            print('⏸️ 下载已暂停或失败，停止进度更新: ${progressRecord.deviceName}');
            return;
          }

          // 大幅减少日志输出，避免控制台刷屏
          final progressPercent = (progressRecord.progress * 100).round();
          if (progressPercent % 10 == 0) {
            print(
              '📊 MP4下载进度更新: ${progressRecord.deviceName} - $progressPercent%',
            );
          }

          // 使用极严格的防抖机制，避免过于频繁的数据库更新
          final recordId = progressRecord.id?.toString() ?? '';
          final now = DateTime.now();
          final lastUpdate = _lastUpdateTime[recordId];

          // 只在以下情况更新数据库：
          // 1. 下载完成
          // 2. 进度变化超过25%
          // 3. 距离上次更新超过15秒
          if (progressRecord.progress >= 1.0 ||
              (progressRecord.progress * 100).round() % 25 == 0 ||
              lastUpdate == null ||
              now.difference(lastUpdate).inSeconds > 15) {
            await _updateDownloadRecord(progressRecord);
            _lastUpdateTime[recordId] = now;
          }
        },
        onComplete: (completedRecord) async {
          print('✅ MP4下载完成: ${completedRecord.deviceName}');
          await _updateDownloadRecord(completedRecord);
          BotToast.showText(text: '下载完成，请前往我的下载进行查看');
        },
        onError: (errorRecord, errorMessage) async {
          print('❌ MP4下载失败: ${errorRecord.deviceName} - $errorMessage');
          await _updateDownloadRecord(errorRecord);
          BotToast.showText(text: '网络环境不佳，请稍后尝试');
        },
      );
    } catch (e) {
      print('❌ 开始MP4下载失败: $e');
      BotToast.showText(text: '网络环境不佳，请稍后尝试');
    }
  }

  /// 更新下载记录
  Future<void> _updateDownloadRecord(DownloadRecord record) async {
    try {
      // 检查记录ID是否存在
      if (record.id == null) {
        print('❌ 更新下载记录失败: record.id 为 null');
        return;
      }

      // ✅ 检查记录是否已被删除（不在列表中）
      final exists = downloadRecords.any((r) => r.id == record.id);
      if (!exists) {
        print('🗑️ 记录已被删除，忽略更新: ${record.deviceName}');
        return;
      }

      print('🔄 更新下载记录: ${record.deviceName} - ${record.status}');
      print('📝 记录ID: ${record.id}');
      print('📁 localPath: ${record.localPath}');

      // 先更新数据库
      await _databaseService.updateDownloadRecord(record);

      // 更新本地列表
      final index = downloadRecords.indexWhere((r) => r.id == record.id);
      if (index >= 0) {
        downloadRecords[index] = record;
        print(
          '📝 更新下载记录: ${record.deviceName} - 进度: ${(record.progress * 100).toInt()}% - 状态: ${record.status}',
        );
        print('📁 更新后localPath: ${downloadRecords[index].localPath}');
      } else {
        // 如果没找到，可能是新记录，添加到列表开头
        downloadRecords.insert(0, record);
        print('📝 添加新下载记录: ${record.deviceName} - 状态: ${record.status}');
      }

      // 强制刷新列表和UI
      downloadRecords.refresh();
      update();

      print('✅ 下载记录更新成功，当前记录数: ${downloadRecords.length}');
      print(
        '📊 记录状态: ${downloadRecords.map((r) => '${r.deviceName}: ${r.status}').toList()}',
      );
    } catch (e) {
      print('❌ 更新下载记录失败: $e');
      print('📝 错误详情: ${e.toString()}');
    }
  }

  /// 暂停下载
  Future<void> pauseDownload(String recordId) async {
    try {
      print('⏸️ 暂停下载: $recordId');

      final record = downloadRecords.firstWhere(
        (r) => r.id?.toString() == recordId,
        orElse: () => throw Exception('未找到对应的下载记录'),
      );

      // 立即更新UI状态，提供即时反馈
      final updatedRecord = record.copyWith(status: DownloadStatus.paused);
      final recordIndex = downloadRecords.indexWhere(
        (r) => r.id?.toString() == recordId,
      );

      if (recordIndex >= 0) {
        downloadRecords[recordIndex] = updatedRecord;
        downloadRecords.refresh();
        update();
        print('✅ UI状态立即更新为暂停');
      }

      // 立即调用服务暂停下载（同步操作）
      _mp4DownloadService.pauseDownload(record.videoUrl);
      print('✅ 下载服务已暂停');

      // 异步更新数据库
      _updateDownloadRecord(updatedRecord);

      print('✅ 暂停下载成功: ${record.deviceName}');
      BotToast.showText(text: '已暂停下载');
    } catch (e) {
      print('❌ 暂停下载失败: $e');
      BotToast.showText(text: '暂停下载失败');
    }
  }

  /// 恢复下载
  Future<void> resumeDownload(String recordId) async {
    try {
      print('▶️ 恢复下载: $recordId');

      final record = downloadRecords.firstWhere(
        (r) => r.id?.toString() == recordId,
        orElse: () => throw Exception('未找到对应的下载记录'),
      );

      // 检查是否已经在下载中
      if (record.status == DownloadStatus.downloading ||
          record.status == DownloadStatus.waiting) {
        print('⚠️ 下载已在进行中: ${record.deviceName}');
        BotToast.showText(text: '下载已在进行中');
        return;
      }

      // 更新记录状态为等待中
      final updatedRecord = record.copyWith(status: DownloadStatus.waiting);

      // 更新数据库和本地列表
      await _updateDownloadRecord(updatedRecord);

      // 统一使用MP4下载服务（后端已处理，直接返回MP4地址）
      print('🎬 使用MP4下载服务恢复下载');
      await _mp4DownloadService.downloadMp4(
        downloadUrl: record.videoUrl,
        deviceName: record.deviceName,
        startTime: record.startTime,
        endTime: record.endTime,
        duration: record.duration,
        recordId: record.id!,
        deviceId: record.deviceId,
        channelId: record.channelId,
        channelName: record.channelName,
        picUrl: record.picUrl,
        onProgress: (progressRecord) async {
          print(
            '📊 恢复下载进度: ${progressRecord.deviceName} - ${progressRecord.progress * 100}%',
          );
          await _updateDownloadRecord(progressRecord);
        },
        onComplete: (completedRecord) async {
          print('✅ 恢复下载完成: ${completedRecord.deviceName}');
          await _updateDownloadRecord(completedRecord);
          BotToast.showText(text: '恢复下载完成: ${completedRecord.fileName}');
        },
        onError: (errorRecord, errorMessage) async {
          print('❌ 恢复下载失败: ${errorRecord.deviceName} - $errorMessage');
          await _updateDownloadRecord(errorRecord);
          BotToast.showText(text: '恢复下载失败: $errorMessage');
        },
      );
    } catch (e) {
      print('❌ 恢复下载失败: $e');
      BotToast.showText(text: '恢复下载失败');
    }
  }

  /// 重试下载 - 在原记录上重试，不创建新记录
  Future<void> retryDownload(String recordId) async {
    try {
      final record = downloadRecords.firstWhere(
        (r) => r.id?.toString() == recordId,
        orElse: () => throw Exception('未找到对应的下载记录'),
      );

      print('🔄 重试下载: ${record.deviceName} (ID: $recordId)');
      BotToast.showText(text: '正在重新下载...');

      // 更新记录状态为等待中，重置进度
      final updatedRecord = record.copyWith(
        status: DownloadStatus.waiting,
        progress: 0.0,
        speed: '0B/s',
        downloadedSize: '0B',
      );

      // 更新数据库和本地列表
      await _databaseService.updateDownloadRecord(updatedRecord);
      final index = downloadRecords.indexWhere((r) => r.id == record.id);
      if (index >= 0) {
        downloadRecords[index] = updatedRecord;
      }

      // 直接使用MP4下载服务，传入现有recordId（不会创建新记录）
      print('🎬 使用MP4下载服务重试下载，recordId: ${record.id}');
      await _mp4DownloadService.downloadMp4(
        downloadUrl: record.videoUrl,
        deviceName: record.deviceName,
        startTime: record.startTime,
        endTime: record.endTime,
        duration: record.duration,
        recordId: record.id!, // ✅ 传入现有recordId，确保在原记录上执行
        userId: record.userId,
        deviceId: record.deviceId,
        channelId: record.channelId,
        channelName: record.channelName,
        picUrl: record.picUrl,
        onProgress: (progressRecord) async {
          print(
            '📊 重试下载进度: ${progressRecord.deviceName} - ${progressRecord.progress * 100}%',
          );
          await _updateDownloadRecord(progressRecord);
        },
        onComplete: (completedRecord) async {
          print('✅ 重试下载完成: ${completedRecord.deviceName}');
          await _updateDownloadRecord(completedRecord);
          BotToast.showText(text: '重新下载完成: ${completedRecord.fileName}');
        },
        onError: (errorRecord, errorMessage) async {
          print('❌ 重试下载失败: ${errorRecord.deviceName} - $errorMessage');
          await _updateDownloadRecord(errorRecord);
          BotToast.showText(text: '重新下载失败: $errorMessage');
        },
      );
    } catch (e) {
      print('❌ 重试下载失败: $e');
      BotToast.showText(text: '重试下载失败: ${e.toString()}');
    }
  }

  /// 播放视频
  Future<void> playVideo(String recordId) async {
    try {
      print('🎬 开始播放视频: $recordId');

      if (recordId.isEmpty) {
        BotToast.showText(text: '播放ID无效');
        return;
      }

      final record = downloadRecords.firstWhere(
        (r) => r.id?.toString() == recordId,
        orElse: () => throw Exception('未找到对应的下载记录'),
      );

      if (record.status != DownloadStatus.completed) {
        BotToast.showText(text: '视频尚未下载完成');
        return;
      }

      // 检查本地文件路径
      if (record.localPath == null || record.localPath!.isEmpty) {
        print('❌ 本地文件路径为空: ${record.deviceName}');
        BotToast.showText(text: '本地文件路径不存在');
        return;
      }

      // 检查文件是否存在
      final file = File(record.localPath!);
      if (!await file.exists()) {
        print('❌ 本地文件不存在: ${record.localPath}');
        BotToast.showText(text: '本地文件不存在');
        return;
      }

      // 获取文件信息
      final fileSize = await file.length();
      print('📁 本地文件信息:');
      print('  路径: ${record.localPath}');
      print('  大小: ${_formatBytes(fileSize)}');
      print('  设备: ${record.deviceName}');
      print('  时间: ${record.startTime} - ${record.endTime}');

      // 显示视频播放弹出框（根据平台选择不同的播放器）
      _showVideoPlayerDialog(record);

      // BotToast.showText(text: '正在播放本地TS视频: ${record.fileName}');
    } catch (e) {
      print('❌ 播放视频失败: $e');
      BotToast.showText(text: '播放失败: $e');
    }
  }

  /// 显示视频播放弹出框（根据平台选择不同的播放器）
  void _showVideoPlayerDialog(DownloadRecord record) {
    // 根据平台选择不同的播放器
    Widget playerDialog;
    if (Platform.isIOS) {
      // iOS平台使用media_kit播放器
      playerDialog = VideoPlayerDialogIOS(record: record);
    } else {
      // Android平台使用video_player播放器
      playerDialog = VideoPlayerDialogAndroid(record: record);
    }

    Get.dialog(
      playerDialog,
      barrierDismissible: true,
      barrierColor: Colors.black.withOpacity(0.8),
      useSafeArea: false,
    ).then((_) {
      // 对话框关闭后确保恢复到竖屏模式
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
      SystemChrome.setEnabledSystemUIMode(
        SystemUiMode.manual,
        overlays: SystemUiOverlay.values,
      );
    });
  }

  /// 格式化字节数
  String _formatBytes(int bytes) {
    if (bytes < 1024) return '${bytes}B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)}KB';
    if (bytes < 1024 * 1024 * 1024)
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)}MB';
    return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)}GB';
  }

  /// 删除下载记录
  Future<void> deleteDownload(String recordId) async {
    try {
      print('🗑️ 开始删除下载记录: $recordId');

      final record = downloadRecords.firstWhere(
        (r) => r.id?.toString() == recordId,
        orElse: () => throw Exception('未找到对应的下载记录'),
      );

      print('📋 删除记录详情: ${record.deviceName}, 状态: ${record.status}');

      // ✅ 1. 如果正在下载，立即强制停止（同步操作）
      if (record.status == DownloadStatus.downloading ||
          record.status == DownloadStatus.waiting) {
        print('⚡ 立即强制停止下载: ${record.deviceName}');
        _mp4DownloadService.forceRemoveActiveDownload(record.videoUrl);
        _mp4DownloadService.cancelDownload(record.videoUrl);
      }

      // ✅ 2. 立即从UI中移除，提供即时反馈
      downloadRecords.removeWhere((r) => r.id?.toString() == recordId);
      downloadRecords.refresh();
      update();

      print('✅ 删除下载记录UI更新完成: ${record.deviceName}');
      BotToast.showText(text: '删除成功');

      // ✅ 3. 异步执行后台清理操作（不阻塞UI）
      _asyncCleanup(record);
    } catch (e) {
      print('❌ 删除下载记录失败: $e');
      BotToast.showText(text: '删除失败');
    }
  }

  /// 异步清理下载记录（后台执行，不阻塞UI）
  Future<void> _asyncCleanup(DownloadRecord record) async {
    try {
      // 🗑️ 删除本地文件和临时文件
      await _deleteAllLocalFiles(record);

      // 💾 从数据库删除
      if (record.id != null) {
        await _databaseService.deleteDownloadRecord(record.id!);
        print('✅ 数据库记录删除成功');
      }

      print('✅ 后台清理完成: ${record.deviceName}');
    } catch (e) {
      print('⚠️ 后台清理出现错误: $e');
    }
  }

  /// 删除所有相关的本地文件
  Future<void> _deleteAllLocalFiles(DownloadRecord record) async {
    try {
      print('🗑️ 开始删除本地文件: ${record.deviceName}');

      // 删除主文件
      if (record.localPath != null && record.localPath!.isNotEmpty) {
        final file = File(record.localPath!);
        if (await file.exists()) {
          await file.delete();
          print('✅ 主文件删除成功: ${record.localPath}');
        }
      }

      // 删除可能的临时文件
      await _deleteTemporaryFiles(record);

      print('✅ 所有相关文件删除完成');
    } catch (e) {
      print('⚠️ 删除本地文件时出现错误: $e');
      // 继续执行，不因为文件删除失败而中断整个删除流程
    }
  }

  /// 删除临时文件
  Future<void> _deleteTemporaryFiles(DownloadRecord record) async {
    try {
      final tempDir = await getTemporaryDirectory();
      final hlsTempDir = Directory('${tempDir.path}/hls_temp');

      if (await hlsTempDir.exists()) {
        // 查找与该记录相关的临时文件
        final files = await hlsTempDir.list().toList();

        for (final file in files) {
          final fileName = file.path.split('/').last;
          // 如果文件名包含记录ID或设备名，则删除
          if (fileName.contains(record.id?.toString() ?? '') ||
              fileName.contains(record.deviceName.replaceAll(' ', '_'))) {
            try {
              await file.delete(recursive: true);
              print('🗑️ 删除临时文件: $fileName');
            } catch (e) {
              print('⚠️ 删除临时文件失败: $fileName - $e');
            }
          }
        }
      }
    } catch (e) {
      print('⚠️ 删除临时文件时出现错误: $e');
    }
  }

  /// 清理重复的等待中记录
  Future<void> cleanDuplicateWaitingRecords() async {
    try {
      final waitingRecords =
          downloadRecords
              .where((r) => r.status == DownloadStatus.waiting)
              .toList();

      // 按URL和时间分组，保留最新的记录
      final Map<String, List<DownloadRecord>> groupedRecords = {};

      for (final record in waitingRecords) {
        final key = '${record.videoUrl}_${record.startTime}_${record.endTime}';
        if (!groupedRecords.containsKey(key)) {
          groupedRecords[key] = [];
        }
        groupedRecords[key]!.add(record);
      }

      // 删除重复的记录
      for (final records in groupedRecords.values) {
        if (records.length > 1) {
          // 保留最新的记录，删除其他的
          records.sort((a, b) => b.createdAt.compareTo(a.createdAt));
          for (int i = 1; i < records.length; i++) {
            final recordToDelete = records[i];
            await deleteDownload(recordToDelete.id?.toString() ?? '');
          }
        }
      }

      print('🧹 清理重复记录完成');
    } catch (e) {
      print('❌ 清理重复记录失败: $e');
    }
  }

  /// 切换筛选
  void changeFilter(int index) {
    selectedFilterIndex.value = index;
  }

  /// 获取筛选后的下载记录
  List<DownloadRecord> get filteredDownloadRecords {
    switch (selectedFilterIndex.value) {
      case 1: // 进行中
        return downloadRecords
            .where(
              (r) =>
                  r.status == DownloadStatus.downloading ||
                  r.status == DownloadStatus.waiting,
            )
            .toList();
      case 2: // 已完成
        return downloadRecords
            .where((r) => r.status == DownloadStatus.completed)
            .toList();
      default: // 全部
        return downloadRecords.toList();
    }
  }

  /// 获取下载统计
  Map<String, int> get downloadStatistics {
    final stats = <String, int>{};
    for (final record in downloadRecords) {
      final status = record.status.toString().split('.').last;
      stats[status] = (stats[status] ?? 0) + 1;
    }
    return stats;
  }

  /// 获取进行中的下载数量
  int get downloadingCount {
    return downloadRecords
        .where(
          (r) =>
              r.status == DownloadStatus.downloading ||
              r.status == DownloadStatus.waiting,
        )
        .length;
  }

  /// 获取已完成的下载数量
  int get completedCount {
    return downloadRecords
        .where((r) => r.status == DownloadStatus.completed)
        .length;
  }

  /// 切换全部下载状态
  Future<void> toggleAllDownloads() async {
    try {
      if (isAllPaused.value) {
        // 恢复所有暂停的下载
        print('▶️ 恢复所有暂停的下载');
        for (final record in downloadRecords) {
          if (record.status == DownloadStatus.paused && record.id != null) {
            await resumeDownload(record.id.toString());
          }
        }
        isAllPaused.value = false;
        BotToast.showText(text: '已恢复所有下载');
      } else {
        // 暂停所有下载中的任务
        print('⏸️ 暂停所有下载中的任务');
        for (final record in downloadRecords) {
          if ((record.status == DownloadStatus.downloading ||
                  record.status == DownloadStatus.waiting) &&
              record.id != null) {
            await pauseDownload(record.id.toString());
          }
        }
        isAllPaused.value = true;
        BotToast.showText(text: '已暂停所有下载');
      }
    } catch (e) {
      print('❌ 切换全部下载状态失败: $e');
      BotToast.showText(text: '操作失败');
    }
  }

  /// 获取切换按钮文本
  String get toggleAllText {
    return isAllPaused.value ? '全部开始' : '全部暂停';
  }

  /// 🚫 已禁用：恢复中断的下载任务（防止删除后自动恢复）
  ///
  /// 原先此方法会在应用启动时自动恢复所有状态为"downloading"的任务，
  /// 但这会导致用户删除正在下载的任务后，应用重启时又自动恢复下载。
  ///
  /// 如果需要手动恢复下载，可以通过重试按钮或恢复按钮来处理。
  Future<void> _resetAbnormalDownloadStatus() async {
    print('🚫 自动恢复下载任务已禁用，防止删除后自动恢复');

    // 可选：将所有异常的"downloading"状态重置为"paused"，避免状态不一致
    try {
      final interruptedDownloads =
          downloadRecords
              .where((record) => record.status == DownloadStatus.downloading)
              .toList();

      if (interruptedDownloads.isNotEmpty) {
        print('📋 发现 ${interruptedDownloads.length} 个异常的下载状态，重置为暂停状态');

        for (final record in interruptedDownloads) {
          final pausedRecord = record.copyWith(
            status: DownloadStatus.paused,
            speed: '0B/s',
          );

          await _databaseService.updateDownloadRecord(pausedRecord);

          final index = downloadRecords.indexWhere((r) => r.id == record.id);
          if (index >= 0) {
            downloadRecords[index] = pausedRecord;
          }
        }

        downloadRecords.refresh();
        print('✅ 异常下载状态重置完成');
      }
    } catch (e) {
      print('⚠️ 重置异常下载状态失败: $e');
    }
  }

  /// 获取当前用户ID
  Future<int> _getCurrentUserId() async {
    try {
      final userService = Get.find<UserService>();
      final userId = userService.userId;
      if (userId != null) {
        return userId;
      } else {
        print('⚠️ 用户未登录，使用默认用户ID: 0');
        return 0;
      }
    } catch (e) {
      print('❌ 获取用户ID失败: $e，使用默认用户ID: 0');
      return 0;
    }
  }
}
